package com.n9.qqonline.sales.service;

import com.n9.qq.android.AqContext;
import com.n9.qq.android.im.msg.Elem;
import com.n9.qq.android.im.msg.RichText;
import com.n9.qq.android.mock.MsgListener;
import com.n9.qq.android.msg_comm.Msg;
import com.n9.qq.android.msg_comm.MsgHead;
import com.n9.qqonline.sales.entity.MsgType;
import com.n9.qqonline.sales.entity.RecvMsg;
import com.vdurmont.emoji.EmojiParser;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author ice
 * @since 2019/3/11 12:12
 */
public class DefaultMsgListener implements MsgListener {

    private RecvMsgService recvMsgService;


    public DefaultMsgListener(RecvMsgService recvMsgService) {
        this.recvMsgService = recvMsgService;
    }



    @Override
    public void onReceived(Msg msg, AqContext context) {
        MsgHead msgHead = msg.msg_head;
        long sender = msgHead.from_uin.get();
        String sendNick = msgHead.from_nick.get();
        long recver = msgHead.to_uin.get();
        long groupCode = msgHead.group_info.group_code.get();
        long msgUid = msgHead.msg_uid.get();
        int msgType = msgHead.msg_type.get();
        long msgSeq = msgHead.msg_seq.get();

        String groupName = context.getTroopNameByCode(groupCode);

        RichText rich_text = msg.msg_body.rich_text;
        StringBuilder textMsg = new StringBuilder();
        rich_text.elems.get().forEach(o ->{
            Elem ele = (Elem) o;
            byte[] bytes = ele.text.str.get().toByteArray();
            if (bytes.length > 0) {
                for (int i = 0; i < bytes.length; i++) {
                    if (bytes[i] == 0x0D) {
                        bytes[i] = 0x0A;
                    }
                }
                try {
                    textMsg.append(new String(bytes, "UTF-8").trim());
                } catch (UnsupportedEncodingException e) {
                    //ignore
                }
            }
        });
        String content = textMsg.toString();

        if (content.length() > 0) {
            //过滤表情字符
            content = EmojiParser.removeAllEmojis(content);
            sendNick = EmojiParser.removeAllEmojis(sendNick);
            groupName = EmojiParser.removeAllEmojis(groupName);

            RecvMsg recvMsg = new RecvMsg();
            recvMsg.setMsgSeq(msgSeq);
            recvMsg.setMsgId(msgUid);
            recvMsg.setSendQQUin(sender);
            recvMsg.setSendNick(sendNick);
            recvMsg.setRecvQQUin(recver);
            recvMsg.setRecvGroupCode(groupCode);
            recvMsg.setRecvGroupName(groupName);
            long msgTime = msgHead.msg_time.get() * 1000L;
            recvMsg.setRecvTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(msgTime)));
            recvMsg.setContent(content);
            recvMsg.setMsgType(MsgType.convert(msgType));

            recvMsgService.save(recvMsg);
        }
    }
}
